﻿using Prism.Commands;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PrismActivationDemo
{
    public class MainWindowViewModel : BindableBase
    {
        private readonly IRegionManager _regionManager;
        private readonly IContainerProvider _containerProvider;
        public DelegateCommand NavigateToViewACommand { get; }
        public DelegateCommand NavigateToViewBCommand { get; }

        public MainWindowViewModel(IRegionManager regionManager, IContainerProvider containerProvider)
        {
            _regionManager = regionManager;
            _containerProvider = containerProvider;
            // 导航命令
            NavigateToViewACommand = new DelegateCommand(() => GoToView(new NavigationItem
            {
                Title = "ViewA",
                TargetView = "PrismActivationDemo.ViewA",
                TargetModule = "ModuleA"
            }));

            NavigateToViewBCommand = new DelegateCommand(() => GoToView(new NavigationItem
            {
                Title = "ViewB",
                TargetView = "PrismActivationDemo.ViewB",
                TargetModule = "ModuleB"
            }));
        }

        /// <summary>
        /// 动态加载和激活视图
        /// </summary>
        private void GoToView(NavigationItem item)
        {
            // 获取目标区域
            var region = _regionManager.Regions["MainRegion"];
            // 检查视图是否存在
            var view = region.GetView(item.TargetView);
            if (view == null)
            {
                var viewType = TypeResolver.Resolve(item.TargetView);
                if (viewType != null)
                {
                    view = _containerProvider.Resolve(viewType);
                    region.Add(view, item.TargetView);
                }
                else
                {
                    throw new InvalidOperationException($"Cannot resolve type {item.TargetView}");
                }
            }

            // 激活视图
            region.Activate(view);
        }
    }

        public class NavigationItem
    {
        public string Title { get; set; }
        public string TargetView { get; set; }
        public string TargetModule { get; set; }
    }

    public static class TypeResolver
    {
        public static Type Resolve(string typeName)
        {
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                var type = assembly.GetType(typeName);
                if (type != null)
                    return type;
            }
            return null;
        }
    }

}
